package com.dudu.dao;

import java.sql.Connection;
import java.util.List;

import net.sf.json.JSONObject;

import com.dudu.model.SmsCode;

import core.CoreDao;
import core.db.DBConnectionUtil;

public class SmsCodeDao {

	public static void main(String[] args) {

	}

	public int insert(CoreDao dao, SmsCode bean) {
		Connection con = null;
		int result = -1;
		try {
			con = DBConnectionUtil.getDBConnection("emate1");
			StringBuffer sql = new StringBuffer(
					"INSERT INTO t_sms_code(phone, code, dead_line)");
			sql.append("VALUES(?, ?, ?)");

			List<JSONObject> list = dao.serviceJsonSql(
					con,
					sql.toString(),
					new Object[] { 
						bean.getPhone(), bean.getCode(), bean.getDead_line()
					});

			JSONObject obj = list.get(0);
			result = obj.optInt("result");

		} catch (Exception ex) {
			ex.printStackTrace();
		} finally {
			DBConnectionUtil.close(null, null, con);
		}
		return result;
	}
	
	public int update(CoreDao dao, SmsCode bean) {

		Connection con = null;
		int result = -1;
		try {
			con = DBConnectionUtil.getDBConnection("emate1");
			
			StringBuffer sql = new StringBuffer(" update t_sms_code set code=?, dead_line=? where phone=? ");
			List<JSONObject> list = dao.serviceJsonSql(con, sql.toString(),
					new Object[] { bean.getCode(), bean.getDead_line(), bean.getPhone() });

			if (list != null && list.size() > 0) {
				list.get(0);
				JSONObject obj = list.get(0);
				result = obj.optInt("result");
			}

		} catch (Exception ex) {
			ex.printStackTrace();
		} finally {
			DBConnectionUtil.close(null, null, con);
		}
		return result;
	}
	
	public int delete(CoreDao dao, String phone) {

		Connection con = null;
		int result = -1;
		try {
			con = DBConnectionUtil.getDBConnection("emate1");
			
			StringBuffer sql = new StringBuffer(" delete from t_sms_code where phone = ?");
			List<JSONObject> list = dao.serviceJsonSql(con, sql.toString(),
					new Object[] { phone });

			if (list != null && list.size() > 0) {
				list.get(0);
				JSONObject obj = list.get(0);
				result = obj.optInt("result");
			}

		} catch (Exception ex) {
			ex.printStackTrace();
		} finally {
			DBConnectionUtil.close(null, null, con);
		}
		return result;
	}

	
	public SmsCode query(CoreDao dao, String phone) {
		Connection con = null;
		SmsCode result = null;
		try {
			con = DBConnectionUtil.getDBConnection("emate1");
			StringBuffer sql = new StringBuffer(
					" select * FROM t_sms_code where phone=?");
			List<JSONObject> list = dao.serviceJsonSql(con, sql.toString(),
					new Object[] { phone });
			if (list != null && list.size() > 0) {
				List<SmsCode> listSms = dao.covertToBean(list, SmsCode.class);
				result = listSms.get(0);
			}
		} catch (Exception ex) {
			ex.printStackTrace();
		} finally {
			DBConnectionUtil.close(null, null, con);
		}
		return result;
	}
	
	
	
}
